/*
 * @(#)FileResource.java $version 2012-3-2
 * 
 * Copyright 2011 RogueDevelopment Gruop. All rights Reserved.
 * ROGUEDEVELOPMENT PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.nadostar.extensions.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.jar.JarFile;

/**
 * @author LEESUNG
 * 
 */
public class FileResource implements Resource {

	private long lastModified;

	private final File source;

	/**
	 * Instantiates a new file resource.
	 * 
	 * @param source
	 *            the source
	 */
	public FileResource(File source) {
		this.source = source;
		this.lastModified = source.lastModified();
	}

	/**
	 * @see com.nhncorp.lucy.common.util.Resource#terminal() {@inheritDoc}
	 */
	public boolean terminal() {
		return source.isFile();
	}

	/**
	 * @see com.nhncorp.lucy.common.util.Resource#name() {@inheritDoc}
	 */
	public String name() {
		return source.getName();
	}

	/**
	 * Checks if is modified.
	 * 
	 * @return true, if is modified
	 */
	public boolean isModified() {
		return source.lastModified() > lastModified;
	}

	/**
	 * Sync.
	 */
	public void sync() {
		lastModified = source.lastModified();
	}

	/**
	 * @see com.nhncorp.lucy.common.util.Resource#children() {@inheritDoc}
	 */
	public Collection<Resource> children() throws Exception {
		File[] files = source.listFiles();

		if (files == null) {
			return Collections.emptyList();
		}

		List<Resource> resources = new LinkedList<Resource>();

		for (File file : files) {
			if (file.getName().endsWith(".jar")) {
				resources.add(JarNode.build(new JarFile(file)));
			} else {
				resources.add(new FileResource(file));
			}
		}

		return resources;
	}

	/**
	 * @see com.nhncorp.lucy.common.util.Resource#resource() {@inheritDoc}
	 */
	public URL resource() throws Exception {
		return source.toURL();
	}

	/**
	 * @see com.nhncorp.lucy.common.util.Resource#openStream() {@inheritDoc}
	 */
	public InputStream openStream() throws Exception {
		return new FileInputStream(source);
	}

	/**
	 * @see java.lang.Object#toString() {@inheritDoc}
	 */
	public String toString() {
		return source.toString();
	}

	/**
	 * @see java.lang.Object#equals() {@inheritDoc}
	 */
	@Override
	public boolean equals(Object obj) {
		if (obj == this) {
			return true;
		}

		if (!(obj instanceof FileResource)) {
			return false;
		}

		return this.source.equals(((FileResource) obj).source);
	}

	/**
	 * @see java.lang.Object#hashCode() {@inheritDoc}
	 */
	@Override
	public int hashCode() {
		return this.source.hashCode();
	}

}
